package yxy.cherry.usercenter;

import com.alibaba.fastjson.parser.ParserConfig;

import yxy.apple.database.DAOAccountManager;
import yxy.apple.database.DAOGameManager;
import yxy.apple.database.DAOManager;
import yxy.apple.database.DAOSDKManager;
import yxy.apple.http.server.HttpServer;
import yxy.apple.http.server.business.RequestDispatcher;
import yxy.apple.http.server.converter.ConverterImpl;
import yxy.apple.logger.Logger;
import yxy.apple.util.redisson.FastjsonCodec;
import yxy.apple.util.redisson.RedisConnection;
import yxy.banana.launcher.Reactable;
import yxy.cherry.game.base.mq.MqManager;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;

public class Reactor implements Reactable<Configuration> {

	protected static Logger logger = Logger.create(Reactor.class);

	public static final Reactor instance = new Reactor();

	private HttpServer server = null;

	protected Reactor() {

	}

	public void shutdown() {
		if (this.server != null) {
			logger.info("正在关闭HTTP服务...");
			this.server.stop();
		}
	}

	public void start(Configuration configuration) throws Exception {
		ParserConfig.getGlobalInstance().setAutoTypeSupport(true);

		logger.info("正在初始化数据库连接1...");
		DAOManager.init(configuration.DBAccountConfig);
		logger.info("正在初始化数据库连接2...");
		DAOAccountManager.init(configuration.DBAccountConfig);
		logger.info("正在初始化数据库连接3...");
		DAOGameManager.init(configuration.DBGameConfig);
		logger.info("正在初始化数据库连接4...");
		DAOSDKManager.init(configuration.DBSDKConfig);

		logger.info("正在初始化Redis连接...");
		initRedis(configuration);
		logger.info("正在初始化MQ连接...");
		initMQ(configuration);


		logger.info("正在加载SDK包...");
		RequestDispatcher.getInstance().initAdapter(configuration.SDKpackageName);
		RequestDispatcher.getInstance().setConverter(new ConverterImpl(configuration.Converters));

		logger.info("启动服务器...");
		HttpServerInitializer initializer = new HttpServerInitializer();
		this.server = new HttpServer(configuration.HTTPServer.Port, configuration.HTTPServer.Threads, initializer.provideSslContext());
		this.server.start();
	}

	private void initMQ(Configuration config) throws Exception {
		MqManager.getInstance().init(config.MqConfig);
	}
	
	private void initRedis(Configuration config) throws Exception {
		{
			RedisConnection redisUser = new RedisConnection();
			redisUser.connect(config.UserRedis.Address, config.UserRedis.Password, config.UserRedis.Database, true, new FastjsonCodec());
			RedisManager.getInstance().addConnection(RedisType.REDIS_USER, redisUser);
		}
		{
			RedisConnection redisGame = new RedisConnection();
			redisGame.connect(config.GameRedis.Address, config.GameRedis.Password, config.GameRedis.Database, true, new FastjsonCodec());
			RedisManager.getInstance().addConnection(RedisType.REDIS_GAME, redisGame);
		}
	}

}
